<template>
  <div class="material-page">
    <h1>原料管理</h1>
    <el-card>
      <template #header>
        <div class="flex-between">
          <span>原料搜索</span>
          <div>
            <el-input 
              v-model="searchQuery"
              placeholder="搜索原料名称"
              style="width: 300px; margin-right: 10px"/>
            <el-input 
              v-model="searchId"
              placeholder="搜索原料ID"
              style="width: 200px; margin-right: 10px"/>
            <el-button type="primary" @click="searchMaterial">搜索名称</el-button>
            <el-button type="primary" @click="searchMaterialById">搜索ID</el-button>
            <el-button @click="resetSearch">重置</el-button>
            <el-button type="primary" @click="handleAdd">添加原料</el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="filteredMaterials">  <!-- 修改这里，将materials改为filteredMaterials -->
        <el-table-column prop="id" label="原料ID" width="120" sortable />
        <el-table-column prop="name" label="原料名称" sortable />
        <el-table-column prop="description" label="产品描述" width="200" sortable />
        <el-table-column prop="unit" label="计量单位" width="100" sortable />
        <el-table-column prop="safeStock" label="安全库存" width="100" sortable />
        <el-table-column prop="createTime" label="创建时间" width="180" sortable />
        <el-table-column prop="updateTime" label="更新时间" width="180" sortable />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog v-model="showDialog" :title="dialogTitle">
      <el-form :model="formData" label-width="100px">
        <el-form-item label="原料ID" v-if="isEdit">
          <el-input v-model="formData.id" disabled/>
        </el-form-item>
        <el-form-item label="原料名称">
          <el-input v-model="formData.name"/>
        </el-form-item>
        <el-form-item label="原料描述">
          <el-input v-model="formData.description" type="textarea"/>
        </el-form-item>
        <el-form-item label="计量单位">
          <el-input v-model="formData.unit"/>
        </el-form-item>
        <el-form-item label="安全库存">
          <el-input-number v-model="formData.safeStock" :min="0"/>
        </el-form-item>
       
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="saveMaterial">保存</el-button>
      </template>
    </el-dialog>
    
    <!-- 使用情况对话框 -->
    <el-dialog v-model="showUsageDialog" title="原料使用情况" width="70%">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="原料ID">{{ usageData.material?.id }}</el-descriptions-item>
        <el-descriptions-item label="原料名称">{{ usageData.material?.name }}</el-descriptions-item>
        <el-descriptions-item label="计量单位">{{ usageData.material?.unit }}</el-descriptions-item>
        <el-descriptions-item label="安全库存">{{ usageData.material?.safeStock }}</el-descriptions-item>
      </el-descriptions>
      
      <el-table :data="usageData.usageRecords" style="margin-top: 20px">
        <el-table-column prop="date" label="使用日期" width="120" sortable />
        <el-table-column prop="workOrderId" label="关联工单" width="120" sortable />
        <el-table-column prop="process" label="工序" sortable />
        <el-table-column prop="quantity" label="使用数量" width="120" sortable />
      </el-table>
    </el-dialog>
  </div>
  
  <!-- 在el-dialog下方添加分页组件 -->
  <el-pagination
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    :current-page="pagination.pageNum"
    :page-sizes="[10, 20, 50, 100]"
    :page-size="pagination.pageSize"
    layout="total, prev, pager, next, jumper" background
    :total="pagination.total">
  </el-pagination>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const materials = ref([
  { 
    id: 'MAT001', 
    name: '45号钢', 
    description: '优质碳素结构钢',
    unit: 'kg',
    safeStock: 500,
    relatedProcesses: [
      { id: 'PROC001', name: '粗加工' },
      { id: 'PROC002', name: '精加工' }
    ],
    createTime: '2023-01-01 10:00',
    updateTime: '2023-01-01 10:00'
  }
])

const showDialog = ref(false)
const isEdit = ref(false)
const dialogTitle = ref('添加原料')
const formData = ref({
  id: '',
  name: '',
  description: '',
  unit: '',
  safeStock: 0
  // 移除relatedProcesses字段
})

const handleAdd = () => {
  formData.value = {
    id: '',
    name: '',
    description: '',
    unit: '',
    safeStock: 0
  }
  isEdit.value = false
  dialogTitle.value = '添加原料'
  showDialog.value = true
}

const handleEdit = (material) => {
  formData.value = { 
    id: material.id,
    name: material.name,
    description: material.description,
    unit: material.unit,
    safeStock: material.safeStock
  }
  isEdit.value = true
  dialogTitle.value = '编辑原料'
  showDialog.value = true
}

const saveMaterial = async () => {
  try {
    // 检查原料名称是否已存在
    const isNameAvailable = await checkMaterialName(
      formData.value.name, 
      isEdit.value ? formData.value.id : ''
    );
    
    if (isNameAvailable) {
      ElMessage.error('原料名称已存在，请使用其他名称');
      return;
    }

    const method = isEdit.value ? 'put' : 'post';
    const response = await axios[method]('http://117.72.45.141:8091/api/material', {
      materialName: formData.value.name,
      description: formData.value.description,
      unit: formData.value.unit,
      safetyStock: formData.value.safeStock,
      materialId: isEdit.value ? formData.value.id : undefined
    }, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })

    if (response.data.code === 200) {
      ElMessage.success(isEdit.value ? '原料更新成功' : '原料添加成功')
      showDialog.value = false
      fetchMaterials() // 添加刷新列表
    } else {
      ElMessage.error(response.data.message || '操作失败')
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '操作失败，请检查网络连接')
    console.error('保存原料出错:', error)
  }
}

const searchQuery = ref('')
const searchId = ref('')

const searchMaterialById = async () => {
  if (!searchId.value.trim()) {
    ElMessage.warning('请输入原料ID')
    return
  }

  try {
    const response = await axios.get(`http://117.72.45.141:8091/api/material/${searchId.value}`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })

    if (response.data.code === 200) {
      const material = response.data.data
      materials.value = [{
        id: material.materialId,
        name: material.materialName,
        description: material.description,
        unit: material.unit,
        safeStock: material.safetyStock,
        createTime: material.createTime,
        updateTime: material.updateTime
      }]
      pagination.value.total = 1
    } else {
      ElMessage.error(response.data.message || '未找到该原料')
    }
  } catch (error) {
    console.error('搜索原料出错:', error)
    ElMessage.error('搜索原料出错')
  }
}
const filteredMaterials = computed(() => {
  if (!searchQuery.value) return materials.value
  const query = searchQuery.value.toLowerCase()
  return materials.value.filter(m => 
    m.name.toLowerCase().includes(query) ||
    (m.relatedProcesses && m.relatedProcesses.some(p => 
      p.name.toLowerCase().includes(query)
    ))
  )
})

const showUsageDialog = ref(false)
const usageData = ref({
  material: null,
  usageRecords: []
})

const showUsage = (material) => {
  // 这里应该调用API获取使用记录，目前先用模拟数据
  usageData.value = {
    material,
    usageRecords: [
      { date: '2024-01-10', workOrderId: 'WO001', quantity: 50, process: '粗加工' },
      { date: '2024-01-15', workOrderId: 'WO002', quantity: 30, process: '精加工' }
    ]
  }
  showUsageDialog.value = true
}

// 在script部分添加删除方法
const handleDelete = async (material) => {
  try {
    const response = await axios.delete(`http://117.72.45.141:8091/api/material/${material.id}`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })

    if (response.data.code === 200) {
      ElMessage.success('原料删除成功')
      fetchMaterials() // 添加刷新列表
    } else {
      ElMessage.error(response.data.message || '删除失败')
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '删除失败，请检查网络连接')
    console.error('删除原料出错:', error)
  }
}

// 添加分页相关变量
const pagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

const queryParams = ref({
  materialName: '',
  unit: ''
})

// 添加获取原料列表的方法（分页）
const fetchMaterials = async () => {
  try {
    const response = await axios.post('http://117.72.45.141:8091/api/material/page', {
      materialName: queryParams.value.materialName,
      unit: queryParams.value.unit,
      pageNum: pagination.value.pageNum,
      pageSize: pagination.value.pageSize
    }, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    
    if (response.data.success) {
      materials.value = response.data.data.records.map(item => ({
        id: item.materialId,
        name: item.materialName,
        description: item.description, // 确保包含description
        unit: item.unit,
        safeStock: item.safetyStock,
        createTime: item.createTime,
        updateTime: item.updateTime
      }))
      pagination.value.total = response.data.data.total
    } else {
      ElMessage.error(response.data.message || '获取原料列表失败')
    }
  } catch (error) {
    console.error('获取原料列表出错:', error)
    ElMessage.error('获取原料列表出错')
  }
}

// 监听分页变化
const handleCurrentChange = (val) => {
  pagination.value.pageNum = val
  fetchMaterials()
}

const handleSizeChange = (val) => {
  pagination.value.pageSize = val
  fetchMaterials()
}

const searchMaterial = async () => {
  queryParams.value.materialName = searchQuery.value
  pagination.value.pageNum = 1
  await fetchMaterials()
}

const resetSearch = () => {
  searchQuery.value = ''
  searchId.value = ''
  queryParams.value = {
    materialName: '',
    unit: ''
  }
  pagination.value.pageNum = 1
  fetchMaterials()
}
// 初始化时获取数据
onMounted(() => {
  fetchMaterials()
})

const checkMaterialName = async (name, excludeId = '') => {
  try {
    const response = await axios.get('http://117.72.45.141:8091/api/material/check-name', {
      params: {
        materialName: name,
        excludeId: excludeId
      },
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data.code === 200) {
      return response.data.data; // true表示名称可用，false表示已存在
    }
    return false;
  } catch (error) {
    console.error('检查原料名称出错:', error);
    return false;
  }
}
</script>

<style scoped>
.material-page {
  padding: 20px;
}

:deep(.el-tabs__content) {
  padding-top: 20px;
}

:deep(.el-tabs__item) {
  font-size: 16px;
  font-weight: 500;
}

:deep(.el-tabs__item.is-active) {
  color: #409eff;
}
</style>
